package com.sike.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sike.service.BaseService;
/**
 * @company sikejiaoyu
 * */
@Controller
@RequestMapping(value="user")

public class UserAction extends BaseAction {
	
	private BaseService service;
	
	/**
	 * 实现登陆
	 * */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request){
		
		ModelAndView view = new ModelAndView(); 
		Map<String, Object> map = new HashMap<String, Object>();
		view.setViewName("/user/onlinePage");
		return view;
	}
	/**
	 * 实现用户注册
	 * */
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public ModelAndView register(HttpServletRequest request){
		Map<String,Object> map = this.getParameters();
		System.out.println(map);
		this.service.create("Member.create", map);
		HttpSession session = request.getSession();
		session.setAttribute("name", (String)map.get("name"));
		ModelAndView view = new ModelAndView(); 
		view.setViewName("/user/onlinePage");
		return view;
	}
	
	@RequestMapping(value="/validateLogin",method=RequestMethod.POST)
	public ModelAndView validateLogin(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		Map<String,Object> map = this.getParameters();
		Map<String, Object> user = (HashMap<String, Object>)this.service.load("Member.load", map);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		if(user == null){
			out.print("error");
		}else{
			HttpSession session = request.getSession();
			session.setAttribute("name", (String)map.get("name"));
			out.print("success");
		}
		return null;
	}
	/**
	 * 页面跳转
	 * */
	@RequestMapping(value="/goPage")
	public ModelAndView goPage(HttpServletRequest request){
		
		ModelAndView view = new ModelAndView(); 
		String pageName = request.getParameter("pageName");
		
		HttpSession session = request.getSession();
		if(pageName.equals("register")){
			view.setViewName("/user/register");
		}else if(pageName.equals("login")){
			view.setViewName("/user/login");
		}else if(pageName.equals("mySike")){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", session.getAttribute("name"));
			Map<String, Object> user = (HashMap<String, Object>)this.service.load("Member.load", map);
			view.addObject("user", user);
			view.setViewName("/user/person");
		}
		
		return view;
	}
	
	/**
	 * 修改个人资料
	 * */
	@RequestMapping(value="/selfInfo",method=RequestMethod.POST)
	public ModelAndView selfInfo(HttpServletRequest request){
		Map<String,String> map = new HashMap<String,String>();
		MultipartFile file = null;
		MultipartHttpServletRequest multipartRequest = null;
		if (request instanceof MultipartHttpServletRequest) {
			multipartRequest = (MultipartHttpServletRequest) request;
			file = multipartRequest.getFiles("pic").get(0);
		}
		String id = multipartRequest.getParameter("id");
		String email = multipartRequest.getParameter("email");
		String signature = multipartRequest.getParameter("signature");
		String truename = multipartRequest.getParameter("truename");
		String sex = multipartRequest.getParameter("sex");
		String birthday = multipartRequest.getParameter("birthday");
		String address =  multipartRequest.getParameter("address");
		String job = multipartRequest.getParameter("job");
		String phone =  multipartRequest.getParameter("phone");
		String description = multipartRequest.getParameter("description");
		map.put("email", email);
		map.put("signature", signature);
		map.put("truename",truename);
		map.put("sex", sex);
		map.put("birthday", birthday);
		map.put("address", address);
		map.put("job",job);
		map.put("phone", phone);
		map.put("description", description);
		map.put("id", id);
		
		if(!file.isEmpty()){ //在此做文件操作
			
		
			String rootPath = request.getSession().getServletContext().getRealPath("/");
			String rootPathDB = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
			String dir = rootPath + "web/infoPic/"; 
			map.put("pic",rootPathDB + "web/infoPic/" + id + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
			this.fileUpload(file,dir,id);
			
		}
		
		this.service.update("Member.update", map);
		
		
		
		
		
		ModelAndView view = new ModelAndView(); 
		view.setViewName("/user/onlinePage");
		return view;
	}
	
	/**
	 * 验证密码
	 * */
	@RequestMapping(value="/validatePassword",method=RequestMethod.POST)
	public ModelAndView validatePassword(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = this.getParameters();
		System.out.println(map);
		try {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			if(!(map.get("oldPassword").equals(map.get("oldPassword1")))){
				out.print("旧密码错误！");
			}
			if(((String) map.get("password")).length() > 20){
				out.print("新密码长度不能超过20！");
			}
			if(((String) map.get("password")).length() < 6){
				out.print("新密码长度不能少于6位！");
			}
			if(!(((String)map.get("surePassword")).equals((String)map.get("password")))){
				out.print("密码不一致,请确认！");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 修改个人图片
	 * */
	@RequestMapping(value="/pic",method=RequestMethod.POST)
	public ModelAndView pic(HttpServletRequest request){
		Map<String,Object> map = this.getParameters();
		System.out.println(map);
		this.service.update("Member.update", map);
		
		ModelAndView view = new ModelAndView(); 
		view.setViewName("/user/onlinePage");
		return view;
	}
	
	
	@Resource(name="baseService")
	public void setService(BaseService service) {
		this.service = service;
	}
	
	public boolean fileUpload(MultipartFile file,String dir,String name){
		String fileName = file.getOriginalFilename();
		String suffer = fileName.substring(fileName.lastIndexOf("."));
		fileName = name + suffer;
		
		boolean t = false;
		long size = file.getSize();  
		byte[] data = new byte[(int) size]; 
		try {
			InputStream input = file.getInputStream();
			input.read(data);
			File outFile = new File(dir+fileName);
			File dirFile = new File(dir);
			if(!dirFile.exists()){
				dirFile.mkdirs();
			}
			 if(!outFile.exists()) {
				 t = outFile.createNewFile();  
			 }else{
				 outFile.delete();
				 t = outFile.createNewFile();  
			 }
			 FileOutputStream outStream = new FileOutputStream(outFile);  
			 outStream.write(data);  
			 outStream.close();  
			 input.close();  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		File f = new File(dir);
//		if(!f.exists()){
//			f.mkdirs();
//		}
//		File f2 = new File(dir+fileName);
	
		return t;
	}
	
	
}
